package config

import (
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/widuu/goini"
)

//ServerInfo 服务器配置
type ServerInfo struct {
	IP   string
	Port string
}

//DbConfig 数据库配置
type DbConfig struct {
	ConfigCloudAddr string
	ParkCloudAddr   string
	LocalConfigAddr string
	EbillsAddr      string
	I2pAddr         string
	MallPointsAddr  string
}

//RedisConn redis配置
type RedisServer struct {
	Addr string
}

//LogInfo 日志配置
type LogInfo struct {
	Level     string
	IsConsole string
	Path      string
	Num       string
	Max       string
	FileName  string
	ID        string
	SockURL   string
}

//RedisCache redis缓存配置
type RedisCache struct {
	AccessToken string
	LastTime    int64
	IP          string
}

//Server 服务器配置
var Server ServerInfo

//DBConf 数据库配置
var DBConf DbConfig

//Log 日志配置
var Log LogInfo
var LogKinds []string
var RedisConfig RedisServer
var PageSize int64

func initRedis(cfg *goini.Config) {
	RedisConfig.Addr = cfg.GetValue("Redis", "addr")
}

//InitServer 服务器初始化配置
func InitServer() error {
	conf := goini.SetConfig("config/app.ini")
	Server.IP = conf.GetValue("ServerInfo", "ip")
	Server.Port = conf.GetValue("ServerInfo", "port")

	//配置DB
	DBConf.ConfigCloudAddr = conf.GetValue("DB", "config_cloud_addr")
	DBConf.ParkCloudAddr = conf.GetValue("DB", "park_cloud_addr")
	DBConf.LocalConfigAddr = conf.GetValue("DB", "local_config_addr")
	DBConf.I2pAddr = conf.GetValue("DB", "i2p_addr")
	DBConf.EbillsAddr = conf.GetValue("DB", "ebills_addr")
	DBConf.MallPointsAddr = conf.GetValue("DB", "mall_points_addr")

	PageSize, _ = strconv.ParseInt(conf.GetValue("pages", "perpage"), 10, 64)

	//配置log
	logkinds_str := conf.GetValue("LogInfo", "logKinds")
	LogKinds = strings.Split(logkinds_str, ",")

	if len(LogKinds) == 1 && len(LogKinds[0]) == 0 {
		fmt.Println("日志种类未配置")
		os.Exit(1)
	}

	Log.FileName = conf.GetValue("LogInfo", "filename")
	Log.Level = conf.GetValue("LogInfo", "level")
	Log.ID = conf.GetValue("LogInfo", "id")
	Log.IsConsole = conf.GetValue("LogInfo", "isConsole")
	Log.Max = conf.GetValue("LogInfo", "max")
	Log.Num = conf.GetValue("LogInfo", "num")
	Log.Path = conf.GetValue("LogInfo", "path")
	Log.SockURL = conf.GetValue("LogInfo", "SockUrl")

	initRedis(conf)
	return nil
}

//InitConfig 初始化配置文件
func InitConfig() {
	InitServer()
}
